package com.jieshen.chat;

import java.io.*;
import java.net.Socket;

public class Send implements Runnable {
    //从键盘获取数据
    private BufferedReader br;
    //发送数据的数据流
    private DataOutputStream dos;
    //检查线程是否出错
    private boolean flag = true;

    public Send() {
        br = new BufferedReader(new InputStreamReader(System.in));
    }

    public Send(Socket client) {
        this();//调用本类的无参构造方法
        try {
            dos = new DataOutputStream(client.getOutputStream());
        } catch (IOException e) {
            flag = false;
            CloseUtil.closeAll(dos,client);
        }
    }

    public String getMessage() {
        String str = "";
        try {
            str = br.readLine();
        } catch (IOException e) {
            flag = false;
            CloseUtil.closeAll(br);
        }
        return str;
    }

    private void send(String str){
        try {
            dos.writeUTF(str);
            dos.flush();//清空缓存
        } catch (IOException e) {
            flag = false;
            CloseUtil.closeAll(dos);
        }
    }

    @Override
    public void run() {
        //
        while (flag){
            //调用发送信息的方法
            this.send(getMessage());
        }
    }
}
